<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="baidu-site-verification" content="4OYpSWALtb">
<meta name="theme-color" content="#222">
<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>

<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/zxmLogo.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/zxmLogo.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/zxmLogo.png?v=5.1.4">






  <meta name="keywords" content="vue,vue-cli,">










<meta name="description" content="前言注：适用于windows系统本文讲述要点：  vue-cli项目搭建基本环境配置； 常用插件描述及分享； 项目运行、调试及打包； 项目配置及优化；">
<meta name="keywords" content="vue,vue-cli">
<meta property="og:type" content="article">
<meta property="og:title" content="vue项目搭建及基本配置">
<meta property="og:url" content="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2019/03/27/vue项目搭建及基本配置/index.html">
<meta property="og:site_name" content="Lomo | 朱幸民">
<meta property="og:description" content="前言注：适用于windows系统本文讲述要点：  vue-cli项目搭建基本环境配置； 常用插件描述及分享； 项目运行、调试及打包； 项目配置及优化；">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://flowing_eyes.gitee.io/images/posts/vue运行成功.png">
<meta property="og:image" content="https://flowing_eyes.gitee.io/images/posts/echartsDemo.png">
<meta property="og:updated_time" content="2019-04-16T05:59:33.648Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue项目搭建及基本配置">
<meta name="twitter:description" content="前言注：适用于windows系统本文讲述要点：  vue-cli项目搭建基本环境配置； 常用插件描述及分享； 项目运行、调试及打包； 项目配置及优化；">
<meta name="twitter:image" content="https://flowing_eyes.gitee.io/images/posts/vue运行成功.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2019/03/27/vue项目搭建及基本配置/">





  <title>vue项目搭建及基本配置 | Lomo | 朱幸民</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Lomo | 朱幸民</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">on the way</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-标签">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-分类">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-时间轴">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            时间轴
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-categories" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2019/03/27/vue项目搭建及基本配置/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Lomo 朱幸民">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/headImg.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lomo | 朱幸民">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">vue项目搭建及基本配置</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-27T17:02:16+08:00">
                2019-03-27
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-04-16T13:59:33+08:00">
                2019-04-16
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/前端笔记/" itemprop="url" rel="index">
                    <span itemprop="name">前端笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/03/27/vue项目搭建及基本配置/" class="leancloud_visitors" data-flag-title="vue项目搭建及基本配置">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.6k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  20分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p><font size="2" color="#aaa">注：适用于windows系统</font><br><strong>本文讲述要点：</strong></p>
<ol>
<li>vue-cli项目搭建基本环境配置；</li>
<li>常用插件描述及分享；</li>
<li>项目运行、调试及打包；</li>
<li>项目配置及优化；</li>
</ol>
<a id="more"></a>
<p><strong>适用人群：</strong></p>
<ol>
<li>vue小白；</li>
<li>有html\css\js编程基础；</li>
<li>vue项目整体优化（打包后压缩空间）；</li>
</ol>
<hr>
<h4 id="一、准备阶段"><a href="#一、准备阶段" class="headerlink" title="一、准备阶段"></a>一、准备阶段</h4><p><font size="2" color="#aaa">准备阶段会将项目环境配置完毕,包含<code>node</code>、<code>npm</code>、<code>webpack</code>和<code>vue-cli</code>。已经完成的小伙伴可以跳过此步骤看第二阶段。</font></p>
<h5 id="1-安装node及npm"><a href="#1-安装node及npm" class="headerlink" title="1.安装node及npm"></a>1.安装<code>node</code>及<code>npm</code></h5><p>&emsp;&emsp;从node.js中文网下载并安装<a href="http://nodejs.cn/download/" title="nodejs" target="_blank" rel="noopener">nodejs</a>点击下载<code>.msi</code>的32/64位安装包，然后双击本地文件一路点击<code>下一步</code>完成<code>nodeJs</code>的安装即可。<font size="2" color="#ff6666">注意安装8.10以上版本哟!</font><br>安装完成后，打开命令行工具，输入<code>node -v</code>，如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">E:\&gt;node -v</span><br><span class="line">v8.12.0		//版本号</span><br></pre></td></tr></table></figure></p>
<p>顺便在此处继续输入<code>npm -v</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">E:\&gt;npm -v</span><br><span class="line">6.4.1		//版本号</span><br></pre></td></tr></table></figure></p>
<p>你会惊讶的发现<code>npm</code>已经神奇的安装完成了。这是因为<code>npm</code>在安装<code>nodeJs</code>的时候顺带已经装好了。</p>
<h5 id="2-安装webpack"><a href="#2-安装webpack" class="headerlink" title="2.安装webpack"></a>2.安装<code>webpack</code></h5><p><font size="2" color="blue">注：以下所有<code>npm</code>操作，由于国内速度较慢甚至出现失败，可用淘宝镜像<code>cnpm</code>替代。下列所有<code>npm</code>命令，用<code>cnpm</code>替代即可。方式如下：</font><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install -g cnpm --registry=https://registry.npm.taobao.org</span><br></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;继续刚才的命令行工具，输入<code>npm install webpack -g</code>，<code>-g代表全局安装</code>。安装完成后继续输入<code>webpack -v</code>，出现相应版本号，代表安装成功。<br>我在安装时出现如下状况：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:</span><br><span class="line"> - webpack-cli (https://github.com/webpack/webpack-cli)</span><br><span class="line">   The original webpack full-featured CLI.</span><br><span class="line">We will use &quot;npm&quot; to install the CLI via &quot;npm install -D&quot;.</span><br><span class="line">Do you want to install &apos;webpack-cli&apos; (yes/no):</span><br></pre></td></tr></table></figure></p>
<p>解决方案是：输入<code>npm install  webpack-cli -g</code>。安装成功后执行<code>webpack -v</code>查看版本号，如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">E:\&gt;npm install  webpack-cli -g</span><br><span class="line">*</span><br><span class="line">*  安</span><br><span class="line">*  装				省</span><br><span class="line">*  过				略</span><br><span class="line">*  程</span><br><span class="line">*</span><br><span class="line"></span><br><span class="line">E:\&gt;webpack -v</span><br><span class="line">4.29.6	//版本号</span><br></pre></td></tr></table></figure></p>
<h5 id="3-安装vue脚手架vue-cli"><a href="#3-安装vue脚手架vue-cli" class="headerlink" title="3.安装vue脚手架vue-cli"></a>3.安装vue脚手架<code>vue-cli</code></h5><p>&emsp;&emsp;继续上面的命令行工具。接下来就是安装配置今天的主角了，vue脚手架工具<code>vue-cli</code>。方法一样，键入命令行<code>npm install vue-cli -g</code>全局安装，然后输入<code>vue -V</code><font size="1" color="red">注：是大写的<code>-V</code></font>检测是否安装成功。如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">E:\&gt;vue -V</span><br><span class="line">2.9.6		//版本号</span><br></pre></td></tr></table></figure></p>
<h5 id="4-小结"><a href="#4-小结" class="headerlink" title="4.小结"></a>4.小结</h5><p>&emsp;&emsp;至此，我们已经完成了准备阶段的工作。主要完成的是<code>node</code>、<code>npm</code>、<code>webpack</code>和<code>vue-cli</code>四个工具的环境配置。目前为止，我们在命令行工具的总结应该是如下：<font color="#aaa" size="1">版本号不必一致</font><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">E:\&gt;node -v</span><br><span class="line">v8.12.0</span><br><span class="line"></span><br><span class="line">E:\&gt;npm -v</span><br><span class="line">6.4.1</span><br><span class="line"></span><br><span class="line">E:\&gt;webpack -v</span><br><span class="line">4.29.6</span><br><span class="line"></span><br><span class="line">E:\&gt;vue -V</span><br><span class="line">2.9.6</span><br></pre></td></tr></table></figure></p>
<hr>
<h4 id="二、项目搭建"><a href="#二、项目搭建" class="headerlink" title="二、项目搭建"></a>二、项目搭建</h4><p><font size="1" color="#aaa">本阶段讲述<code>vue-cli</code>项目搭建及相关配置，包含<code>创建项目</code>、<code>修改基础配置</code>、<code>项目运行</code>三个模块，可自行选择阅读或跳过。</font></p>
<h5 id="1-项目创建"><a href="#1-项目创建" class="headerlink" title="1.项目创建"></a>1.项目创建</h5><p>&emsp;&emsp;建立一个空文件夹，最好以纯英文命名。例，我项目路径为<code>E&gt;stydy</code>。打开命令行工具，<code>cd</code>到该文件目录下，执行<code>vue init webpack name</code>，<code>name</code>可替换为你要创建的项目名。回车之后，会要求输入一系列的信息，大部分可直接回车略过，注释如下，没有注释的回车略过即可：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy&gt;vue init webpack blog</span><br><span class="line"></span><br><span class="line">? Project name blog	//项目名</span><br><span class="line">? Project description A Vue.js project	//项目简介</span><br><span class="line">? Author xuan0146 &lt;zxm0146@163.com&gt;	//作者</span><br><span class="line">? Vue build runtime</span><br><span class="line">? Install vue-router? Yes	//使用项目路由</span><br><span class="line">? Use ESLint to lint your code? No	//不开启ESLint语法检测 注意选No</span><br><span class="line">? Set up unit tests Yes</span><br><span class="line">? Pick a test runner jest</span><br><span class="line">? Setup e2e tests with Nightwatch? Yes</span><br><span class="line">? Should we run `npm install` for you after the project has been created? (recommended) npm</span><br><span class="line"></span><br><span class="line">   vue-cli · Generated &quot;blog&quot;.</span><br></pre></td></tr></table></figure></p>
<p>最后一步选择<code>npm</code>或者<code>yarn</code>则会自动执行<code>npm install</code>安装项目所有依赖包。不选择的话，自己安装也是同样效果。安装步骤为：</p>
<ol>
<li><code>cd</code>到项目路径；</li>
<li>执行<code>npm install</code>；</li>
<li>等待完成安装即可;</li>
</ol>
<h5 id="2-项目介绍"><a href="#2-项目介绍" class="headerlink" title="2.项目介绍"></a>2.项目介绍</h5><p>&emsp;&emsp;<code>cd</code>到该项目，或者打开文件夹，项目目录及备注如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">├── project	//项目目录</span><br><span class="line">│  ├── build	//webpack相关配置</span><br><span class="line">│  │  ├── build.js	//生产环境构建</span><br><span class="line">│  │  ├── check-versions.js	//版本检查</span><br><span class="line">│  │  ├── utils.js	//构建相关工具</span><br><span class="line">│  │  ├── vue-loader.conf.js	//处理vue文件的配置信息</span><br><span class="line">│  │  ├── webpack.base.conf.js	//webpack基础配置</span><br><span class="line">│  │  ├── webpack.dev.conf.js	//webpack开发环境配置</span><br><span class="line">│  │  ├── webpack.prod.conf.js	//webpack生产环境配置</span><br><span class="line">│  ├── config	//vue基本配置</span><br><span class="line">│  │  ├── dev.env.js	//开发环境配置</span><br><span class="line">│  │  ├── index.js	//主要配置</span><br><span class="line">│  │  ├── prod.env.js	//生产环境配置</span><br><span class="line">│  │  ├── test.env.js	//测试环境配置</span><br><span class="line">│  ├── node_modules	//依赖包 忽略</span><br><span class="line">│  ├── src	//项目核心文件</span><br><span class="line">│  │  ├── assets	//静态资源 如公用js\css\image\媒体资源等</span><br><span class="line">│  │  ├── components	//公用组件</span><br><span class="line">│  │  ├── router	//项目路由</span><br><span class="line">│  │  │  ├── index.js	//路由控制文件</span><br><span class="line">│  │  ├── App.vue	//根组件</span><br><span class="line">│  │  ├── main.js	//入口文件</span><br><span class="line">│  ├── static	//静态资源</span><br><span class="line">│  ├── test	//模拟测试</span><br><span class="line">│  ├── .babelrc	//babel参数</span><br><span class="line">│  ├── .editorconfig	//代码格式</span><br><span class="line">│  ├── .gitignore	//git上传相关配置</span><br><span class="line">│  ├── .postcssrc.js	//css相关工具</span><br><span class="line">│  ├── index.html	//主页</span><br><span class="line">│  ├── package-lock.json	//记录当前状态下实际安装的各个npm package的具体来源和版本号</span><br><span class="line">│  ├── package.json	//项目信息</span><br><span class="line">│  ├── README.md	//项目说明</span><br></pre></td></tr></table></figure></p>
<h5 id="3-启动项目"><a href="#3-启动项目" class="headerlink" title="3.启动项目"></a>3.启动项目</h5><p>&emsp;&emsp;命令行工具键入<code>npm run dev</code>，等待片刻，直到提示如下，则表示启动成功：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;npm run dev</span><br><span class="line"></span><br><span class="line">* * * * * * * *</span><br><span class="line">* 启动过程忽略 *</span><br><span class="line">* * * * * * * *</span><br><span class="line"></span><br><span class="line">Your application is running here: http://localhost:8080</span><br></pre></td></tr></table></figure></p>
<p>然后复制<code>http://localhost:8080</code>，在浏览器地址栏输入该url，进入如下页面：<br><img src="/images/posts/vue运行成功.png" alt="vue运行成功" title="vue运行成功"></p>
<h5 id="4-移动端调试"><a href="#4-移动端调试" class="headerlink" title="4.移动端调试"></a>4.移动端调试</h5><p>&emsp;&emsp;有的人可能要问了，如果我做移动端项目，不能用localhost去访问了吧？当然不能，只需要稍微改一下配置即可。当然，端口号8080一样可以修改，不过一般不做变动。<br>&emsp;&emsp;用代码工具（自己习惯的IDE）打开本项目。首先查看本机电脑ip,键入命令<code>ipconfig</code>，查看如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;ipconfig</span><br><span class="line">* *</span><br><span class="line">* *</span><br><span class="line">以太网适配器 以太网:</span><br><span class="line"></span><br><span class="line">   连接特定的 DNS 后缀 . . . . . . . :</span><br><span class="line">   本地链接 IPv6 地址. . . . . . . . : fe80::da7:800d:d148:e06%10</span><br><span class="line">   IPv4 地址 . . . . . . . . . . . . : 192.168.200.127</span><br><span class="line">   子网掩码  . . . . . . . . . . . . : 255.255.255.0</span><br><span class="line">   默认网关. . . . . . . . . . . . . : fe80::48:5112:9520:564f%10</span><br><span class="line">                                       192.168.200.1</span><br></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;其中，<code>IPv4 地址</code>即为我们所需要的ip。在<code>项目/config/index.js</code>中，找到<code>host: &#39;localhost&#39;</code>，改成<code>IPv4 地址</code>，例:我的地址为<code>192.168.200.127</code>:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">module.exports = &#123;</span><br><span class="line">  dev: &#123;</span><br><span class="line">    host: &apos;192.168.200.127&apos;, 	//localhost改为ip</span><br><span class="line">    port: 8080,		//端口号</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;然后，我们重新启动项目。注意上次项目启动后，由于修改了配置文件，因此需要停止项目然后重新启动。停止项目的命令为<code>Ctrl + C</code>。重启项目后，如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;npm run dev</span><br><span class="line">* * * * * * * *</span><br><span class="line">* 启 动 过 程 *</span><br><span class="line">* * * * * * * *</span><br><span class="line">Your application is running here: http://192.168.200.127:8080</span><br></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;<font size="2" color="#aaa">注意要在同一网络下</font><br>&emsp;&emsp;最后，我们复制该地址，即可在所有端<code>PC</code>、<code>手机</code>、<code>pad等</code>查看该项目啦~</p>
<hr>
<h4 id="三、常用插件"><a href="#三、常用插件" class="headerlink" title="三、常用插件"></a>三、常用插件</h4><p><font size="1" color="#aaa">本章节记录一些vue常用插件，如<code>axios</code>、<code>echarts</code>、<code>sass/scss</code>、<code>lib-flexible</code>等等。所有命令均可用<code>cnpm</code>替代。如不需要可直接跳过。</font></p>
<h5 id="1-sacc-scss"><a href="#1-sacc-scss" class="headerlink" title="1.sacc/scss"></a>1.sacc/scss</h5><p><strong>用途</strong>：可用<code>sass/scss</code>进行css书写代码。命令行工具依次键入如下命令：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm install node-sass --save-dev</span><br><span class="line">npm install sass-loader --save-dev</span><br></pre></td></tr></table></figure></p>
<p>安装完成后，<code>.vue</code>里的<code>style</code>里添加<code>lang=&quot;scss&quot;</code>来指定语言，即可用<code>sass/scss</code>编写css代码。如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;style lang=&quot;scss&quot; scoped&gt;</span><br><span class="line">...</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure></p>
<h5 id="2-axios"><a href="#2-axios" class="headerlink" title="2.axios"></a>2.axios</h5><p><strong>用途</strong>：平时前后端交互使用<code>Ajax</code>，在vue官方，给出<code>vue-resource</code>和<code>axios</code>的作为<code>ajax</code>的替代。在此处使用vue官方推荐首选的<code>axios</code>作为案例讲述。</p>
<ul>
<li><p>安装</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install axios</span><br></pre></td></tr></table></figure>
</li>
<li><p>全局引入<br>在<code>项目/src/main.js</code>中引入如下代码，然后随意走个请求，发现……报错？并且在页面F12控制台<code>Newwork&gt;Headers</code>里面发现数据并没有Form Data形式提交，如何处理呢？见下一步解决。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">import axios from &apos;axios&apos;</span><br></pre></td></tr></table></figure>
</li>
<li><p>解决数据格式问题</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">//完整请求代码  post为例</span><br><span class="line">this.$axios.post(&apos;url&apos;, &#123;	//路径</span><br><span class="line">  key1: &apos;value&apos;,		//参数</span><br><span class="line">  key2: &apos;value&apos;		//参数</span><br><span class="line">&#125;, </span><br><span class="line"></span><br><span class="line">/* *</span><br><span class="line">* 添加如下代码</span><br><span class="line">* * * * * * start * * * * * </span><br><span class="line">&#123;</span><br><span class="line">  transformRequest: [function (data) &#123;</span><br><span class="line">    let ret = &apos;&apos;;</span><br><span class="line">    for (let it in data) &#123;</span><br><span class="line">	  ret += encodeURIComponent(it) + &apos;=&apos; + encodeURIComponent(data[it]) + &apos;&amp;&apos;;</span><br><span class="line">    &#125;</span><br><span class="line">    return ret</span><br><span class="line">    &#125;</span><br><span class="line">  ],</span><br><span class="line">  headers: &#123;</span><br><span class="line">    &apos;Content-Type&apos;: &apos;application/x-www-form-urlencoded&apos;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* * * * * * end * * * * *</span><br><span class="line"></span><br><span class="line">).then((response) =&gt; &#123;	//返回数据</span><br><span class="line">  console.log(response)</span><br><span class="line">&#125;).catch((error) =&gt; &#123;	//请求异常捕捉</span><br><span class="line">  console.log(error)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="3-axios解决方案"><a href="#3-axios解决方案" class="headerlink" title="3.axios解决方案"></a>3.axios解决方案</h5><p>&emsp;&emsp;另外一个axios数据格式问题的解决方案。 <code>重磅推荐★★★★★</code>此方案不仅解决数据格式问题，还顺便解决了跨域问题。第一步当然还是安装<code>axios</code>，同上一步。然后，安装<code>qs</code>，命令行工具键入<code>npm install qs --save-dev</code>。然后在<code>项目/src/main.js</code>中配置如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">import axios from &apos;axios&apos;</span><br><span class="line">import qs from &apos;qs&apos;	</span><br><span class="line"></span><br><span class="line">Vue.prototype.$axios = axios;</span><br><span class="line">Vue.prototype.$qs = qs;</span><br></pre></td></tr></table></figure></p>
<p>然后在<code>项目/config/index.js</code>中，找到<code>proxyTable</code>，配置及说明如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">proxyTable: &#123;</span><br><span class="line">  &apos;/api&apos;: &#123;</span><br><span class="line">    //设置url公用部分</span><br><span class="line">    target: &apos;http://192.168.1.100:8080/&apos;,	</span><br><span class="line">    changeOrigin: true,   // 如果接口跨域，需要进行这个参数配置</span><br><span class="line">    pathRewrite: &#123;</span><br><span class="line">      &apos;^/api&apos;: &apos;&apos;      //这里理解成用‘/api’代替target里面的地址</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure></p>
<p>配置完成之后，在<code>.vue</code>文件中，请求用例如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">//参数</span><br><span class="line">let params = this.$qs.stringify(&#123;</span><br><span class="line">  key: value</span><br><span class="line">&#125;);</span><br><span class="line">//请求</span><br><span class="line">this.$axios.post(&apos;/api/test&apos;, params).then((response) =&gt; &#123;</span><br><span class="line">  console.log(response);</span><br><span class="line">&#125;).catch((error) =&gt; &#123;</span><br><span class="line">  console.log(error);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>最后，键入命令<code>npm run dev</code>，发现请求数据格式已经成为<code>Form Data</code>的格式，并且即使后端不处理跨域问题，也依然正常可用。原因是<code>proxy</code>作为中间层，先将数据请求回本地，此过程是中间层node请求后台，不存在跨域。然后请求过来的数据放在本地，前端再去请求这个数据，就可以解决跨域问题了。</p>
<h5 id="4-echarts可视化"><a href="#4-echarts可视化" class="headerlink" title="4.echarts可视化"></a>4.echarts可视化</h5><p>&emsp;&emsp;如今相信大家不少项目需要用到数据可视化吧？各种统计图表、炫酷可视化效果等等，都需要一个不错的插件去支撑，比如<code>D3</code>、<code>AnyChart</code>、<code>echarts</code>、<code>HighCharts</code>等等。本案例用百度的<code>echarts</code>作为案例讲解。</p>
<ul>
<li>安装依赖<br>惯例，先装依赖。命令行工具执行<code>npm install echarts --save-dev</code>。</li>
<li><p>全局配置<br>安装完成后，全局引入。引入方法：进入<code>项目/src/main.js</code>，如下操作：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">import echarts from &apos;echarts&apos;</span><br><span class="line"></span><br><span class="line">Vue.prototype.$echarts = echarts</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用<br>在<code>***.vue</code>组件中即可正常使用。我在此处用<code>Hello.vue</code>写示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">//template</span><br><span class="line">&lt;div id=&quot;demo&quot;&gt;&lt;/div&gt;</span><br><span class="line"></span><br><span class="line">//script</span><br><span class="line">let myChart = this.$echarts.init(document.getElementById(&apos;demo&apos;)); //初始化</span><br><span class="line">//myChart.clear();	//根据需求配置</span><br><span class="line">myChart.setOption(&#123; // 图表配置</span><br><span class="line">  xAxis: &#123;</span><br><span class="line">    type: &apos;category&apos;,</span><br><span class="line">    data: [&apos;Mon&apos;, &apos;Tue&apos;, &apos;Wed&apos;, &apos;Thu&apos;, &apos;Fri&apos;, &apos;Sat&apos;, &apos;Sun&apos;]</span><br><span class="line">  &#125;,</span><br><span class="line">  yAxis: &#123;</span><br><span class="line">    type: &apos;value&apos;</span><br><span class="line">  &#125;,</span><br><span class="line">  series: [&#123;</span><br><span class="line">    data: [820, 932, 901, 934, 1290, 1330, 1320],</span><br><span class="line">    type: &apos;line&apos;,</span><br><span class="line">    smooth: true</span><br><span class="line">  &#125;]</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">//style</span><br><span class="line">#demo&#123;</span><br><span class="line">  width: 500px;</span><br><span class="line">  height: 500px;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>效果图<br><img src="/images/posts/echartsDemo.png" alt="echarts效果图" title="echarts效果图"></p>
</li>
<li>按需引入<br>试过之后会发现echarts的包很大，会导致打包之后文件过大，因此如果不是刚需的情况下，建议按需引入来完成页面，会节省许多资源及开销。首先，将刚才<code>项目/src/main.js</code>中的两行代码注释掉。接下来，依然以<code>Hello.vue</code>举例，如下：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">//template &amp;&amp; style 不作变动</span><br><span class="line"></span><br><span class="line">//script</span><br><span class="line">const echarts = require(&apos;echarts/lib/echarts&apos;);	//基本模板</span><br><span class="line">require(&apos;echarts/lib/chart/line&apos;);	//折线图组件</span><br><span class="line">require(&apos;echarts/lib/component/title&apos;);	//标题组件</span><br><span class="line"></span><br><span class="line"> // 初始化实例</span><br><span class="line">let myChart = echarts.init(document.getElementById(&apos;demo&apos;));</span><br><span class="line">// 图表配置</span><br><span class="line">myChart.setOption(&#123;</span><br><span class="line">  title: &#123; text: &apos;引入title组件可使用标题&apos; &#125;,</span><br><span class="line">  * * * * * * * *</span><br><span class="line">  * 别的配置不变 *</span><br><span class="line">  * * * * * * * *</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="5-lib-flexible-px2rem-loader"><a href="#5-lib-flexible-px2rem-loader" class="headerlink" title="5.lib-flexible | px2rem-loader"></a>5.lib-flexible | px2rem-loader</h5><p>&emsp;&emsp;lib-flexible作用在于写页面的时候实现自适应效果，包括文图排本等。需要配合<code>px2rem-loader</code>使用。步骤如下：</p>
<ul>
<li><p>安装依赖</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">npm i lib-flexible --save-dev</span><br><span class="line"></span><br><span class="line">npm install px2rem-loader --save-dev</span><br></pre></td></tr></table></figure>
</li>
<li><p>引入<br><code>项目/src/main.js</code>中做如下配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">import &apos;lib-flexible</span><br></pre></td></tr></table></figure>
</li>
<li><p>主页添加视口配置<br><code>项目/index.html</code>中的<code>head</code>中添加：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>px2rem配置<br><code>项目/build/utils.js</code>中如下配置，然后重启项目即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">//自适应字体配置</span><br><span class="line">const px2remLoader = &#123;</span><br><span class="line">  loader: &apos;px2rem-loader&apos;,</span><br><span class="line">  options: &#123;</span><br><span class="line">    remUnit: 37.5   //设计稿的宽度除以 10，现阶段一般设计稿的宽度都为750px。如果基于iPhone5设计则为32.0(320 / 10 = 32)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function generateLoaders (loader, loaderOptions) &#123;</span><br><span class="line">  const loaders = options.usePostCSS ? [cssLoader, postcssLoader, px2remLoader] : [cssLoader, px2remLoader]</span><br><span class="line"></span><br><span class="line">  * * *</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>更多关于<strong><em>px2rem</em></strong>的介绍请移步<strong><a href="https://www.npmjs.com/package/px2rem" target="_blank" rel="noopener">官网</a></strong></p>
</li>
</ul>
<hr>
<h4 id="四、项目打包"><a href="#四、项目打包" class="headerlink" title="四、项目打包"></a>四、项目打包</h4><p><font size="1" color="#aaa">本章节介绍<code>打包</code>以及去除打包后资源中的<code>.map</code>文件。</font><br>开发完成后，怎么打包到线上呢？emm…this is a problem.</p>
<h5 id="1-打包"><a href="#1-打包" class="headerlink" title="1.打包"></a>1.打包</h5><p>命令行工具<code>cd</code>到该项目下，执行<code>npm run build</code>来构建项目：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;npm run build</span><br><span class="line"></span><br><span class="line">                                                  Asset       Size  Chunks                    Chunk Names</span><br><span class="line">               static/js/vendor.38756a8637fc194013f9.js     442 kB       0  [emitted]  [big]  vendor</span><br><span class="line">                  static/js/app.0b5326236ed4caddb252.js     1.1 kB       1  [emitted]         app</span><br><span class="line">             static/js/manifest.2ae2e69a05c33dfc65f8.js  857 bytes       2  [emitted]         manifest</span><br><span class="line">    static/css/app.26e0081e2c66d97635076ad7fefbb5b6.css  164 bytes       1  [emitted]         app</span><br><span class="line">static/css/app.26e0081e2c66d97635076ad7fefbb5b6.css.map  348 bytes          [emitted]</span><br><span class="line">           static/js/vendor.38756a8637fc194013f9.js.map    2.38 MB       0  [emitted]         vendor</span><br><span class="line">              static/js/app.0b5326236ed4caddb252.js.map    8.47 kB       1  [emitted]         app</span><br><span class="line">         static/js/manifest.2ae2e69a05c33dfc65f8.js.map    4.97 kB       2  [emitted]         manifest</span><br><span class="line">                                             index.html  571 bytes          [emitted]</span><br><span class="line"></span><br><span class="line">  Build complete.</span><br></pre></td></tr></table></figure></p>
<h5 id="2-位置"><a href="#2-位置" class="headerlink" title="2.位置"></a>2.位置</h5><p>打包完成后，去哪儿了呢？然后会发现在项目路径下，出现了一个<code>dist</code>的文件夹，这里面就是所谓的<strong><em> 包 </em></strong>了。如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">├── project	</span><br><span class="line">│  ├── build	</span><br><span class="line">│  ├── config	</span><br><span class="line">│  ├── dist		// 包	</span><br><span class="line">│  │  ├── static	// 压缩后的资源</span><br><span class="line">│  │  ├── index.html	// 主页</span><br><span class="line">│  ├── node_modules	</span><br><span class="line">│  ├── src	</span><br><span class="line">│  ├── static	</span><br><span class="line">│  ├── test	</span><br><span class="line">│  ├── .babelrc	</span><br><span class="line">│  ├── .editorconfig	</span><br><span class="line">│  ├── .gitignore	</span><br><span class="line">│  ├── .postcssrc.js	</span><br><span class="line">│  ├── index.html	</span><br><span class="line">│  ├── package-lock.json	</span><br><span class="line">│  ├── package.json	</span><br><span class="line">│  ├── README.md</span><br></pre></td></tr></table></figure></p>
<h5 id="3-问题-amp-解决"><a href="#3-问题-amp-解决" class="headerlink" title="3.问题&amp;解决"></a>3.问题&amp;解决</h5><p>细心的你可能发现了，<code>dist/static/css(或js)</code>里面，每个css文件和js文件下有一个同名的<code>.map</code>文件，非常占空间，那它是做什么的呢？又怎么消除呢？</p>
<ul>
<li>作用<br>查过资料的小伙伴知道了，<code>.map</code>文件的作用就是：<strong>项目打包后，代码都是经过压缩加密的，如果运行时报错，输出的错误信息无法准确得知是哪里的代码报错。有了map就可以像未加密的代码一样，准确的输出是哪一行哪一列有错。</strong></li>
<li><p>如何解决<br>那么该如何处理这些文件呢？进入<code>项目/config/index.js</code>，定位到<code>productionSourceMap</code>，将其值改为<code>false</code>即可。如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">productionSourceMap: false,</span><br></pre></td></tr></table></figure>
</li>
<li><p>重新打包验证<br>在命令行工具重新执行<code>npm run build</code>，发现<code>.map</code>文件已经消失，问题解决。如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;npm run build</span><br><span class="line"></span><br><span class="line">                                              Asset       Size  Chunks                    Chunk Names</span><br><span class="line">           static/js/vendor.38756a8637fc194013f9.js     442 kB       0  [emitted]  [big]  vendor</span><br><span class="line">              static/js/app.3c96ecd23cc6dc073a3e.js    1.05 kB       1  [emitted]         app</span><br><span class="line">         static/js/manifest.2ae2e69a05c33dfc65f8.js  799 bytes       2  [emitted]         manifest</span><br><span class="line">static/css/app.26e0081e2c66d97635076ad7fefbb5b6.css   95 bytes       1  [emitted]         app</span><br><span class="line">                                         index.html  571 bytes          [emitted]</span><br><span class="line"></span><br><span class="line">  Build complete.</span><br></pre></td></tr></table></figure>
</li>
</ul>
<hr>
<h4 id="五、包优化"><a href="#五、包优化" class="headerlink" title="五、包优化"></a>五、包优化</h4><p>&emsp;&emsp;在项目逐渐壮大之后，虽然说上面已经讲述过了如何去除<code>.map</code>文件，但是其中许多<code>.js</code>文件的体积也不容小觑。尤其是发布到线上以后，某些css/js单个文件体积极可能超上兆的大小，如果项目服务器带宽不够，但是页面迸发量不低的话，分分钟就可能挂掉。有没有什么方法能进一步将包优化呢？</p>
<h5 id="1-gzip打包压缩"><a href="#1-gzip打包压缩" class="headerlink" title="1.gzip打包压缩"></a>1.gzip打包压缩</h5><ul>
<li><p>安装gzip<br>惯例，打开命令行工具，安装<code>gzip</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install compression-webpack-plugin@1.1.11 --save-dev</span><br></pre></td></tr></table></figure>
</li>
<li><p>配置<br><code>项目/config/index.js</code>中，定位到<code>productionGzip</code>，改为<code>true</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">productionGzip: true,</span><br></pre></td></tr></table></figure>
</li>
<li><p>重新打包<br><code>npm run build</code>走起，会发现打包的文件中多了同名的<code>.gz</code>文件，体积大概压缩了2/3，很棒的体验。如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;npm run build</span><br><span class="line"></span><br><span class="line">                                              Asset       Size  Chunks                    Chunk Names</span><br><span class="line">           static/js/vendor.38756a8637fc194013f9.js     442 kB       0  [emitted]  [big]  vendor</span><br><span class="line">              static/js/app.3c96ecd23cc6dc073a3e.js    1.05 kB       1  [emitted]         app</span><br><span class="line">         static/js/manifest.2ae2e69a05c33dfc65f8.js  799 bytes       2  [emitted]         manifest</span><br><span class="line">static/css/app.26e0081e2c66d97635076ad7fefbb5b6.css   95 bytes       1  [emitted]         app</span><br><span class="line">                                         index.html  571 bytes          [emitted]</span><br><span class="line">        static/js/vendor.38756a8637fc194013f9.js.gz     155 kB          [emitted]</span><br><span class="line"></span><br><span class="line">  Build complete.</span><br></pre></td></tr></table></figure>
</li>
<li><p>nginx配置<br>虽然很给力的节省了许多资源，但是需要运维配合，在<code>gninx.conf</code>配置文件中做如下配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">http &#123;  </span><br><span class="line">  gzip on;</span><br><span class="line">  gzip_disable &quot;msie6&quot;; </span><br><span class="line">  gzip_vary on; </span><br><span class="line">  gzip_proxied any;</span><br><span class="line">  gzip_comp_level 8;  //压缩级别</span><br><span class="line">  gzip_buffers 16 8k;</span><br><span class="line">  #gzip_http_version 1.1;</span><br><span class="line">  gzip_min_length 100; //不压缩临界值</span><br><span class="line">  gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h5 id="2-采用cdn加速"><a href="#2-采用cdn加速" class="headerlink" title="2.采用cdn加速"></a>2.采用cdn加速</h5><p>&emsp;&emsp;顾名思义，即将一些比较大的插件放在第三方服务器上去加载，这样不仅快很多，也能更加节约自己的服务器资源及宽带资源。我们一般选用<code>unpkg</code>或者<code>BootCDN</code>来作为第三方。在此处我们使用<code>BootCDN</code>来作为第三方加速使用。想了解更多相关知识请点击<strong><a href="https://unpkg.com" target="_blank" rel="noopener">unpkg</a></strong> <strong><a href="https://www.bootcdn.cn/" target="_blank" rel="noopener">BootCDN</a></strong>。</p>
<ul>
<li>查找包<br>打开<strong><a href="https://www.bootcdn.cn/" target="_blank" rel="noopener">BootCDN</a></strong>，在搜索栏搜索想要的第三方资源。如，我想要替换的是<code>echarts</code>、<code>Vue</code>、<code>axios</code>，则依次搜索<code>echarts</code>…，然后查找我想要的版本，然后<code>复制&lt;script&gt;标签</code>。</li>
<li><p>插入<br>在<code>项目/index.html</code>中将标签插入，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;</span><br><span class="line">//插入在这里</span><br><span class="line">&lt;script src=&quot;https://cdn.bootcss.com/vue/2.5.20/vue.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;script src=&quot;https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;script src=&quot;https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts-en.common.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;script src=&quot;https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>webpack配置<br>打开<code>项目/build/webpack.base.conf.js</code>中，添加<code>externals</code>:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">module.exports = &#123;</span><br><span class="line">  context: path.resolve(__dirname, &apos;../&apos;),</span><br><span class="line">  //..	</span><br><span class="line">  externals:&#123;</span><br><span class="line">    &apos;vue&apos;: &apos;Vue&apos;,</span><br><span class="line">    &apos;vue-router&apos;: &apos;VueRouter&apos;,</span><br><span class="line">    &apos;echarts&apos;:&apos;echarts&apos;,</span><br><span class="line">    &apos;axios&apos;:&apos;axios&apos;,</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>main配置<br>打开<code>项目/src/main.js</code>，将<code>Vue</code>等注释掉即可。不注释也可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">// import Vue from &apos;vue&apos;</span><br></pre></td></tr></table></figure>
</li>
<li><p>打包<br>最后，见证奇迹的时刻就要到了~</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">E:\stydy\blog&gt;npm run build</span><br><span class="line"></span><br><span class="line">                                              Asset       Size  Chunks             Chunk Names</span><br><span class="line">           static/js/vendor.1f9d0533037be66c61cf.js    12.3 kB       0  [emitted]  vendor</span><br><span class="line">              static/js/app.912fd568ff845fde7c09.js    1.36 kB       1  [emitted]  app</span><br><span class="line">         static/js/manifest.2ae2e69a05c33dfc65f8.js  799 bytes       2  [emitted]  manifest</span><br><span class="line">static/css/app.edc64bd802cdc531977a30fcc8a9d6e1.css   62 bytes       1  [emitted]  app</span><br><span class="line">                                         index.html  876 bytes          [emitted]</span><br><span class="line">        static/js/vendor.1f9d0533037be66c61cf.js.gz    4.62 kB          [emitted]</span><br><span class="line"></span><br><span class="line">  Build complete.</span><br></pre></td></tr></table></figure>
</li>
<li><p>搞定<br>上次打包，<code>vendor</code>大小为<strong>442kB</strong>，本次打包，疯狂缩小至<strong>12.3kB</strong>。神不神奇~厉不厉害~</p>
</li>
</ul>
<hr>
<h4 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h4><p>&emsp;&emsp;到这里，vue项目从环境配置、项目搭建，到结构介绍、常用插件依赖安装使用做了比较详细的介绍，最后将项目优化也做了一定的补充。<br>&emsp;&emsp;<font color="deepskyblue">学而时习之，温故而知新。</font>至此，以上。</p>

      
    </div>
    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">---本文结束<i class="fa fa-paw"></i>感谢您的阅读---</div>
    
</div>
	  
	</div>
	<div>
		  
			
		  
	</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>请作者喝杯咖啡吧~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Lomo 朱幸民 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Lomo 朱幸民 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/vue/" rel="tag"><i class="fa fa-tag"></i> vue</a>
          
            <a href="/tags/vue-cli/" rel="tag"><i class="fa fa-tag"></i> vue-cli</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/03/25/《面纱》随笔/" rel="next" title="《面纱》随笔">
                <i class="fa fa-chevron-left"></i> 《面纱》随笔
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/09/vue之data中数组改变如何驱动视图/" rel="prev" title="vue之data中数组改变如何驱动视图">
                vue之data中数组改变如何驱动视图 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
	
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/headImg.png" alt="Lomo 朱幸民">
            
              <p class="site-author-name" itemprop="name">Lomo 朱幸民</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">100</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">91</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          <!--
		  */
		  -->



          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xuan0146" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:zxm0146@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/a708dcdb5061" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-book"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5094024813" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
            </div>
          

          
          

          
          

		  <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="298" height="52" src="//music.163.com/outchain/player?type=2&id=756112&auto=1&height=32"></iframe>
		  

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#一、准备阶段"><span class="nav-text">一、准备阶段</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-安装node及npm"><span class="nav-text">1.安装node及npm</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-安装webpack"><span class="nav-text">2.安装webpack</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-安装vue脚手架vue-cli"><span class="nav-text">3.安装vue脚手架vue-cli</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-小结"><span class="nav-text">4.小结</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#二、项目搭建"><span class="nav-text">二、项目搭建</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-项目创建"><span class="nav-text">1.项目创建</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-项目介绍"><span class="nav-text">2.项目介绍</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-启动项目"><span class="nav-text">3.启动项目</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-移动端调试"><span class="nav-text">4.移动端调试</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#三、常用插件"><span class="nav-text">三、常用插件</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-sacc-scss"><span class="nav-text">1.sacc/scss</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-axios"><span class="nav-text">2.axios</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-axios解决方案"><span class="nav-text">3.axios解决方案</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-echarts可视化"><span class="nav-text">4.echarts可视化</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#5-lib-flexible-px2rem-loader"><span class="nav-text">5.lib-flexible | px2rem-loader</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#四、项目打包"><span class="nav-text">四、项目打包</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-打包"><span class="nav-text">1.打包</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-位置"><span class="nav-text">2.位置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-问题-amp-解决"><span class="nav-text">3.问题&amp;解决</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#五、包优化"><span class="nav-text">五、包优化</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-gzip打包压缩"><span class="nav-text">1.gzip打包压缩</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-采用cdn加速"><span class="nav-text">2.采用cdn加速</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#结语"><span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      


    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Lomo 朱幸民</span>

  
</div>








<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共116k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("ivrWycPPaTqpUQWlrrynaC9b-gzGzoHsz", "hEXywpn5sGaCnm5zWsMmEu2j");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
